<?php
/**
 * Description: PhpStorm.
 * Author: momo
 * Date: 7/26/24 9:01 AM
 * Copyright: momo
 */


namespace app\api\controller;


use app\common\enums\ResponseStatusEnum;
use app\common\model\Users;

use EasyWeChat\MiniApp\Application;
use MoCommon\Support\Codes;
use MoCommon\Support\Helper;
use think\facade\Cache;
use think\facade\Log;

class Account
{
    public function login()
    {
        $code = input('code');
        $nickName = input('nickName');
        $userImg = input('userImg','');
        $userGender = input('userGender',0);//性别 0：未知、1：男、2：女
        $config = config('wechat.mini_program.default');
        $app = new Application($config);
        $status = Codes::ACTION_FAL;
        $message = Codes::get(Codes::ACTION_FAL);
        $session = $app->getUtils()->codeToSession($code);
        if (!isset($session['session_key'])) {
            $message = '小程序session_key获取错误';
        } else {
            $userModel = new Users();
            $member = $userModel->oneDetail(Users::class, ['open_id' => $session['openid']]);
            if (empty($member)) {
                //没有账号
                $mtrand=mt_rand(100000,999999);
                $insertData = [
                    "user_phone" => "",
                    "user_name"=>time().$mtrand,
                    "nick_name" => "学员".$mtrand,
                    "user_img" => $userImg,
                    "user_gender" => ($userGender==2?0:1),//未知的默认男
                    "open_id" => $session['openid']
                ];
                $userModel->addOne(Users::class, $insertData);
            }else{
                $updateData = [
                    "user_img" => $userImg,
                    "user_gender" => ($userGender==2?0:1),//未知的默认男
                ];
                //更新数据
                $userModel->updateOne(Users::class,$updateData, ['open_id' => $session['openid']]);
            }
            $member = $userModel->oneDetail(Users::class, ['open_id' => $session['openid']]);
            if (empty($member["user_phone"])) {
                $member["user_phone"] = "";
            }
            $member['session_key'] = $session['session_key'];
            // 给用户生成token
            $sign = Helper::get_token($member['id']);
            //存入redis
            Cache::store('redis')->set($sign, json_encode($member), config('cache.stores.redis.expire'));
            $member["token"] = $sign;
            $status = Codes::ACTION_SUC;
            $message = Codes::get(Codes::ACTION_SUC);

        }
        return json(["status" => $status, "msg" => $message, "data" => $member]);
    }
}
